package com.main.cxf;
import java.util.concurrent.atomic.AtomicInteger; 
 
/** 
 * a simple encrypt and decpypt class 
 *  
 * @author kai 
 *  
 */ 
public class MyWorldTool { 
    static final String DEFAULT_RAW_KEY_PAIR = "568745"; 
    private static String pair_private_key = DEFAULT_RAW_KEY_PAIR; 
    static AtomicInteger curr = new AtomicInteger(0); 
 
    public static void main(String[] args) { 
        if (args.length == 0 || args[0].equals("help")) { 
            System.out 
                    .println("Usage: args[0] your passwd  \n\targs[1]:function chose(0 encryt  and 1 decrypt)  \n\targs[2] is optional  means your own key .by default is 555556 \nargs[2] must be all numbers"); 
            return; 
        } 
        String ga = args[0]; 
        String function = args[1]; 
        if (args.length > 2) { 
            pair_private_key = args[2]; 
        } 
        String retText; 
        if (function.equals("0")) { 
            retText = encry(ga); 
            System.out.println("Encrypt text is \n" + retText + "\n"); 
        } else if (function.equals("1")) { 
            retText = decry(ga); 
            System.out.println("Decrypt text is \n" + retText + "\n"); 
        } 
 
    } 
 
    private static String encry(String pwd) { 
        initCurr(); 
        char[] pwdchar = pwd.toCharArray(); 
        char[] retStr = new char[pwdchar.length]; 
        char[] pairArray = pair_private_key.toCharArray(); 
        int length = pairArray.length; 
        for (int i = 0; i < pwdchar.length; i++) { 
            int currValue = getCurr(); 
            currValue = currValue < length ? currValue : currValue % length; 
            int rawInt = pwdchar[i] + pairArray[currValue] % 48; 
            if (rawInt > 126) { 
                retStr[i] = (char) (rawInt % 126 + 32); 
            } else { 
                retStr[i] = (char) (rawInt); 
            } 
        } 
        return new String(retStr); 
    } 
 
    private static String decry(String text) { 
        initCurr(); 
        char[] textchar = text.toCharArray(); 
        char[] retpwd = new char[textchar.length]; 
        char[] pairArray = pair_private_key.toCharArray(); 
        int length = pairArray.length; 
 
        for (int i = 0; i < textchar.length; i++) { 
            int currValue = getCurr(); 
            currValue = currValue < length ? currValue : currValue % length; 
            int rawInt = textchar[i] - pairArray[currValue] % 48; 
            if (rawInt < 33) { 
                retpwd[i] = (char) (126 - 32 + rawInt); 
            } else { 
                retpwd[i] = (char) (rawInt); 
            } 
        } 
        return new String(retpwd); 
    } 
 
    private static int getCurr() { 
        return curr.getAndIncrement(); 
    } 
 
    private static void initCurr() { 
        curr.set(0); 
    } 
} 